//
//  ComposeTypeView.swift
//  GYXWeibo
//
//  Created by Twisal on 2017/3/30.
//  Copyright © 2017年 Twisal. All rights reserved.
//

import UIKit
import pop

class ComposeTypeView: UIView {
    /// 滚动视图
    @IBOutlet weak var scrollView: UIScrollView!
    /// 返回按钮
    @IBOutlet weak var returnButton: UIButton!
    /// 关闭按钮的水平约束
    @IBOutlet weak var closeBtnCenterXCons: NSLayoutConstraint!
    /// 返回按钮的水平约束
    @IBOutlet weak var returnBtnCenterXCons: NSLayoutConstraint!
    /// 完成回调
    fileprivate var completionBlock: ((_ clsName: String) -> ())?
    /// 按钮数据数组
    fileprivate let buttonsInfo = [["imageName": "tabbar_compose_idea", "title": "文字", "clsName": "GYXComposeViewController"],
                               ["imageName": "tabbar_compose_photo", "title": "照片/视频"],
                               ["imageName": "tabbar_compose_weibo", "title": "长微博"],
                               ["imageName": "tabbar_compose_lbs", "title": "签到"],
                               ["imageName": "tabbar_compose_review", "title": "点评"],
                               ["imageName": "tabbar_compose_more", "title": "更多", "actionName": "clickMore"],
                               ["imageName": "tabbar_compose_friend", "title": "好友圈"],
                               ["imageName": "tabbar_compose_wbcamera", "title": "微博相机"],
                               ["imageName": "tabbar_compose_music", "title": "音乐"],
                               ["imageName": "tabbar_compose_shooting", "title": "拍摄"]
    ]

    /// 类方法
    ///
    /// - Returns: 实例对象, 用xib加载后视图的frame默认为600*600
    class func composeTypeView() -> ComposeTypeView {
        let nib = UINib(nibName: "ComposeTypeView", bundle: nil)
        
        let view = nib.instantiate(withOwner: nil, options: nil)[0] as! ComposeTypeView
        // XIB 加载默认 600 * 600
        view.frame = UIScreen.main.bounds
        view.setupUI()
        return view
    }
    
    
    /// 显示视图
    func show(comletion: @escaping (_ clsName: String?) -> ()) {
        // 1, 记录闭包
        completionBlock = comletion
        // 2, 获取根控制器的视图
        guard let vc = UIApplication.shared.keyWindow?.rootViewController else {
            return
        }
        // 3, 将当前视图tian
        vc.view.addSubview(self)
        
        // 4, 显示添加控件的动画
        showCurrentViewAnimation()
        
    }
    
    
    // MARK: - 监听
    /// 点击其他按钮
    @objc fileprivate func clickButton(selectedButton: GYXComposeTypeButton) {

        // 获取当前的子视图
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]
        
        // 遍历当前视图中的子控件
        for (i, btn) in v.subviews.enumerated() {
            // 创建缩变动画
            let scaleAnim = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
            let scale: CGFloat = (btn == selectedButton) ? 2 : 0.2
            scaleAnim?.toValue = NSValue(cgPoint: CGPoint(x: scale, y: scale))
            scaleAnim?.duration = 0.5
            btn.pop_add(scaleAnim, forKey: nil)
            
            // 创建渐变动画
            let alphaAnim = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            alphaAnim?.toValue = 0.2
            alphaAnim?.duration = 0.5
            btn.pop_add(alphaAnim, forKey: nil)
            
            // 文字按钮
            if i == 0 {
                alphaAnim?.completionBlock = { _, _ in
                    self.completionBlock?(selectedButton.clsName!)
                }
            }
        }
    }
    
    
    /// 点击更多
    @objc fileprivate func clickMore() {
        
        // 设置scrollView的contentOffset
        let offset = CGPoint(x: scrollView.bounds.width, y: 0)
        scrollView.setContentOffset(offset, animated: true)
        
        // 显示返回按钮
        returnButton.isHidden = false
        returnButton.alpha = 1
        let margin = scrollView.bounds.width / 6
        returnBtnCenterXCons.constant -= margin
        closeBtnCenterXCons.constant += margin
        
        UIView.animate(withDuration: 0.25) { 
            self.layoutIfNeeded()
        }
        
    }
    
    /// 移除视图
    @IBAction func close() {
        hideButtonsAnim()
    }
    
    /// 返回第一页
    @IBAction func returnClick() {
        scrollView.setContentOffset(CGPoint(x: 0, y:0), animated: true)
        returnBtnCenterXCons.constant = 0
        closeBtnCenterXCons.constant = 0
        UIView.animate(withDuration: 0.25, animations: { 
            self.layoutIfNeeded()
            self.returnButton.alpha = 1
        }) { (_) in
            self.returnButton.alpha = 0
            self.returnButton.isHidden = true
            
        }
    }
    
}

// MARK: - 页面动画分组
extension ComposeTypeView {
    
    // MARK: 添加视图时的动画
    /// 显示当前视图的动画
    fileprivate func showCurrentViewAnimation() {
        let anim = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        anim?.fromValue = 0
        anim?.toValue = 1
        anim?.duration = 0.25
        pop_add(anim, forKey: nil)
        showButtonsAnim()
    }
    
    /// 显示添加按钮的动画
    private func showButtonsAnim() {
        
        for (i, btn) in scrollView.subviews[0].subviews.enumerated() {
            let anim = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            anim?.fromValue = btn.center.y + 350
            anim?.toValue = btn.center.y
            anim?.beginTime = CACurrentMediaTime() + CFTimeInterval(i) * 0.025
            anim?.springBounciness = 8
            anim?.velocity = 8
            btn.pop_add(anim, forKey: nil)
        }
        
    }
    
    // MARK: 移除视图动画
    
    /// 隐藏按钮的动画
    fileprivate func hideButtonsAnim() {
        
        // 1, 获取容器视图
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]
        
        // 2, 遍历为子控件添加动画
        for (i, btn) in v.subviews.enumerated().reversed() {
            let anim = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            anim?.fromValue = btn.center.y
            anim?.toValue = btn.center.y + 350
            anim?.beginTime = CACurrentMediaTime() + CFTimeInterval(v.subviews.count - i) * 0.025
            anim?.springBounciness = 8
            anim?.velocity = 8
            btn.pop_add(anim, forKey: nil)
            
            // 3, 判断最后一个
            if i == 0 {
                anim?.completionBlock = {_, _ in
                    self.hideCurrentViewAnim()
                }
            }
        }
    }
    
    
    /// 隐藏当前视图
    private func hideCurrentViewAnim() {
        // 创建并添加动画
        let anim = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        anim?.fromValue = 1
        anim?.toValue = 0
        anim?.duration = 0.25
        pop_add(anim, forKey: nil)
        anim?.completionBlock = {_, _ in
            self.removeFromSuperview()
        }
    }
}


// MARK: - 初始化界面
private extension ComposeTypeView {
    func setupUI()  {
        // 强行更新布局
        layoutIfNeeded()
        // 创建按钮容器视图, 设置它的frame
        let rect = scrollView.bounds
        // 获取按钮容器的个数, 每个容器有6个
        let vCount = buttonsInfo.count / 6 + 1
        for i in 0..<vCount {
            // 创建视图
            let v = UIView(frame: rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0))
            // 向view中添加按钮
            addButtons(v: v, idx: i * 6)
            // 向scrollView添加视图
            scrollView.addSubview(v)
        }
        
       // 设置scrollView的contentSize
        scrollView.contentSize = CGSize(width: CGFloat(vCount) * rect.width, height: rect.height)
    }
    
    
    /// 向view中添加按钮
    ///
    /// - Parameter v: 容器
    /// - Parameter idx: 开始的索引
    func addButtons(v: UIView, idx: Int) {
        let count = 6
        
        // 1,从idx开始, 向v中添加6个button
        for i in idx..<idx+count {
            
            // 1>判断是否越界
            if i >= buttonsInfo.count {
                break
            }
            
            // 2>从数组中获取button设置信息
            let dict = buttonsInfo[i]
            guard let imageName = dict["imageName"],
                let title = dict["title"] else {
                    continue
            }
            // 3> 创建button
            let btn = GYXComposeTypeButton.composeTypeButton(imageName: imageName, title: title)
            btn.backgroundColor = superview?.backgroundColor
            // 4> 向视图添加按钮
            v.addSubview(btn)
            
            // 5> 为按钮添加监听
            if let actionName = dict["actionName"] {
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            } else {
                btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
            }
            // 6> 设置要展现的类名 - 注意不需要任何的判断，有了就设置，没有就不设置
            btn.clsName = dict["clsName"]
        }
        
        // 2, 向容器的子视图, 布局子视图
        for (i, btn) in v.subviews.enumerated() {
            // 1>设置button的宽高
            let btnW: CGFloat = 100
            let btnH: CGFloat = 100
            // 2>设置button之间的间隙
            let margin = (v.bounds.width - 3 * btnW) / 4
            // 3> 计算列数
            let col = i % 3
            // 4> 设置button的位置
            let x = CGFloat(col + 1) * margin + CGFloat(col) * btnW
            let y = i > 2 ? (v.bounds.height - btnH) : 0
            // 5> 布局button
            btn.frame = CGRect(x: x, y: y, width: btnW, height: btnH)
        }
    }
}





















